package m.jclecai.com.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;

import java.util.LinkedList;
import java.util.List;

import m.jclecai.com.R;
import m.jclecai.com.bean.ResIssueList;
import m.jclecai.com.inter.OnResultListener;
import m.jclecai.com.utils.DecimalUtil;
import m.jclecai.com.utils.ToastUtil;

/**
 * Created by hp on 2017/4/17.
 */

public class ContinuousBuyAdapter extends BaseAdapter implements View.OnClickListener, EditText.OnEditorActionListener {

    private final Context context;
    private final OnResultListener listener;
    private final int mTotalMoney;

    //期号
    private String term;
    int termInt;  //期号的整形表示形式；
    //倍数
    private List<String> bs;
    //总投入和之前的投入是一个值，
    // 这样写只是利于我们计算当前累计的投入；
    //总投入,
    List<Integer> invests;
    //之前投入
    List<Integer> beforeInvest;

    //玩法对应盈利的金额；
    private final int mBonus;
    private List<String> mIssueList;

    public ContinuousBuyAdapter(Context context, OnResultListener listener, int bonus,int totalMoney) {
        this.context = context;
        this.listener = listener;
        //这里我们设置为金额，不在使用mode;
        mBonus = bonus;
        mTotalMoney = totalMoney;
    }

    public void setData(List<String> bs, String term) {
        this.term = term;
        this.bs = bs;
        termInt = Integer.parseInt(term);
        invests = new LinkedList<>();
        beforeInvest = new LinkedList<>();
        calculate();
    }


    @Override
    public int getCount() {
        return bs.size();
    }

    @Override
    public Object getItem(int position) {
        return bs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int profit = 0; //盈利
        double percent = 0; //盈利率
        String multiple; //倍数
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(context, R.layout.continuous_buy_item, null);
            holder.et_count = (EditText) convertView.findViewById(R.id.et_count);
            holder.et_count.setOnEditorActionListener(this);

            holder.et_count.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    String s1 = s.toString();
                    //防止0开头数字
                    if (!s1.isEmpty()) {
                        int len = s1.length();
                        if (len == 1 && s1.equals("0")) {
                            s.clear();
                        }
                    }
                }
            });
            holder.tv_add = (TextView) convertView.findViewById(R.id.tv_add);
            holder.tv_add.setOnClickListener(this);
            holder.tv_deduct = (TextView) convertView.findViewById(R.id.tv_deduct);
            holder.tv_deduct.setOnClickListener(this);
            holder.tv_tab_one = (TextView) convertView.findViewById(R.id.tv_tab_one);
            holder.tv_tab_two = (TextView) convertView.findViewById(R.id.tv_tab_two);
            holder.tv_tab_three = (TextView) convertView.findViewById(R.id.tv_tab_three);
            holder.tv_tab_four = (TextView) convertView.findViewById(R.id.tv_tab_four);
            holder.tv_tab_five = (TextView) convertView.findViewById(R.id.tv_tab_five);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tv_add.setTag(holder);
        holder.tv_deduct.setTag(holder);
        holder.et_count.setTag(holder);
        holder.et_count.setText(DecimalUtil.clearPoint(Double.parseDouble(bs.get(position))) + "");
        holder.tv_tab_one.setText(String.valueOf(position + 1)); //序号

        if (mIssueList != null) {
            String issue = mIssueList.get(position);
            holder.tv_tab_two.setText(issue.substring(issue.length()-2)); //追号期次
        }else{
            holder.tv_tab_two.setText("0");
        }

        multiple = holder.et_count.getText().toString();
        holder.tv_tab_three.setText(String.valueOf(invests.get(position)));

        if(multiple.isEmpty()){
            profit=mBonus-invests.get(position);
        }else{
            profit=mBonus*Integer.parseInt(multiple)-invests.get(position);
        }

        if (profit > 0) {
            holder.tv_tab_four.setTextColor(Color.parseColor("#429D4D"));
        } else {
            holder.tv_tab_four.setTextColor(Color.parseColor("#FB4E46"));
        }
        holder.tv_tab_four.setText(String.valueOf(profit));

        double div = DecimalUtil.div(profit, invests.get(position), 4);
        percent = DecimalUtil.mul(div, 100);
        if (percent > 0) {
            holder.tv_tab_five.setTextColor(Color.parseColor("#429D4D"));
        } else {
            holder.tv_tab_five.setTextColor(Color.parseColor("#FB4E46"));
        }
        holder.tv_tab_five.setText(percent + "%");
        return convertView;
    }

    @Override
    public void onClick(View v) {
        ViewHolder holder = (ViewHolder) v.getTag();
        switch (v.getId()) {
            case R.id.tv_add:
                addAndDeduct(holder, true);
                break;
            case R.id.tv_deduct:
                addAndDeduct(holder, false);
                break;
        }
    }


    private void addAndDeduct(ViewHolder holder, boolean isAdd) {
        String s = holder.et_count.getText().toString();
        int number = Integer.parseInt(s);
        //加
        if (isAdd) {
            holder.et_count.setText(String.valueOf(number + 1));
        } else {
            if (number > 1) {
                holder.et_count.setText(String.valueOf(number - 1));
            }
        }
        int position = Integer.parseInt(holder.tv_tab_one.getText().toString());
        bs.remove(position - 1);
        bs.add(position - 1, holder.et_count.getText().toString());
        setData(bs, term);
        notifyDataSetChanged();
    }

    private void calculate() {
        int totalMoney = 0;
        invests.clear();
        beforeInvest.clear();
        for (int i = 0; i < bs.size(); i++) {
            int b = DecimalUtil.clearPoint(Double.parseDouble(bs.get(i)));
            if (i == 0) {
                //这个计算有问题，当前总钱数*倍数
                invests.add(mTotalMoney * b);
            } else {
                invests.add(mTotalMoney * b + beforeInvest.get(i - 1));
            }
            beforeInvest.add(invests.get(i));
            totalMoney += invests.get(i);
        }
        //这里返回的是总共投入的金额
        listener.onReturnResult(invests.get(invests.size()-1)+"");
        //listener.onReturnResult(totalMoney+"");
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        ViewHolder holder = (ViewHolder) v.getTag();
        //获取点击的位置
        int position = Integer.parseInt(holder.tv_tab_one.getText().toString());
        //清除改位置上原有的倍数
        bs.remove(position - 1);
        //获取输入的倍数
        String b = v.getText().toString();
        if (!b.isEmpty()) {
            int i = Integer.parseInt(b);
            if (i <= 99999) {
                bs.add(position - 1, v.getText().toString());
            } else {
                holder.et_count.setText("99999");
                bs.add(position - 1, "99999");
                ToastUtil.showToast(context, "倍数超过最大限制");
            }
        } else {
            holder.et_count.setText("1");
            bs.add(position - 1, "1");
        }
        setData(bs, term);
        notifyDataSetChanged();

        return true;
    }

    public void refreshIssueList(ResIssueList resIssueList) {

        //这里是期号列表的数据；
        mIssueList = resIssueList.getIssue();
        notifyDataSetChanged();
    }


    private class ViewHolder {
        TextView tv_tab_one;
        TextView tv_tab_two;
        TextView tv_tab_three;
        TextView tv_tab_four;
        TextView tv_tab_five;
        EditText et_count;
        TextView tv_add;
        TextView tv_deduct;
    }
}
